const koa2Req = require('koa2-request');
const jwt = require('jsonwebtoken')

const seq = require('../db/seq');
const User = require('../model/user');
const { JWT_SECRET } = require('../config/config.default');

const user = User(seq);

class UserController {
    //用户登录接口
    async login(ctx, next) {
        // 接收appid,appsecret,code
        const { APPID, SECRET, JSCODE } = ctx.request.body
        try {
            // 组合url
            const url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + APPID + '&secret=' + SECRET + '&js_code=' + JSCODE + '&grant_type=authorization_code'
            // 向微信服务器发送请求
            const res1 = await koa2Req(url);
            // 获取session_key和openid
            const { openid } = JSON.parse(res1.body);
            //如果数据库中不存在该用户id就将该用户的openid存入数据库中
            const res2 = await user.findOne({ attributes: ['user_id'], where: { user_id: openid } });
            if (!res2) {
                const res3 = await user.create({ user_id: openid });
            }
            const info = { user_id: openid };
            ctx.body = {
                code: 0,
                message: '用户登录成功',
                result: {
                    token: jwt.sign(info, JWT_SECRET, { expiresIn: '30d' })
                }
            };
        } catch (err) {
            console.log('用户登录失败', err);
            return ctx.body = {
                error: '用户登录失败'
            }
        }

    }

    //获取用户信息接口
    async getInfo(ctx, next) {
        const user_id = ctx.state.user.user_id;
        const res = await user.findOne({
            attributes: ['user_name', 'user_integral', 'user_sex', 'user_age'],
            where: {
                user_id: user_id
            }
        });
        ctx.body = {
            code: 0,
            message: '获取用户信息成功',
            result: res
        }
    }

    //修改用户信息接口
    async updateInfo(ctx, next) {
        const user_id = ctx.state.user.user_id;
        console.log(user_id)
        const info = ctx.request.body;
        console.log(info);
        try {
            const res = await user.update(info, { where: { user_id: user_id } });
            ctx.body = {
                code: 0,
                message: '更新信息成功',
                result: res
            }
        } catch {
            console.log('更新信息失败');
            return ctx.body = {
                error: '更新信息失败'
            }
        }
    }
}

module.exports = new UserController();